<template>
  <div class="value-table-root">
    <el-table
        :data="readOnly ? showList : [...showList,{mergeRow:true}]"
        border
        :span-method="arraySpanMethod"
        style="width: 100%">
      <el-table-column
          v-for="(item,index) in valueConfig"
          :prop="item.value"
          :label="item.label">
        <template slot-scope="scope">
          <div v-if="scope.row.mergeRow" class="handel-row">
            <el-button type="primary" size="mini" @click="handleAdd">添加</el-button>
          </div>
          <div v-else>
            <show-file-list :show-close="false" :uid="form.rowId" v-if="item.type=='file'"
                            :file-list="allFileList.find(fileItem => fileItem.uid == `${scope.row.rowId}-${item.value}`) == null ? [] : allFileList.find(fileItem => fileItem.uid == `${scope.row.rowId}-${item.value}`).fileList"
                            @delFile="delFile"></show-file-list>
            <span v-if="item.type == 'input' || item.type=='txtArea' || item.type == 'number'  || item.type == 'time'">
              {{ scope.row[item.value] }}
            </span>
            <span v-if="item.type == 'choose-question'">
              {{ getQuestionLabelById(scope.row[item.value]) }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column
          :width="handWidth"
          v-if="!readOnly || isArr(btList)"
          label="操作">
        <template slot-scope="scope">
          <el-button
              size="mini"
              v-if="!readOnly"
              type="text"
              icon="el-icon-edit"
              @click="updateRow(scope.row)"
          >修改
          </el-button>
          <el-button
              size="mini"
              type="text"
              v-if="!readOnly"
              icon="el-icon-delete"
              @click="removeRow(scope.row)"
          >删除
          </el-button>

          <div v-if="isArr(btList)">
            <el-button
                v-for="(item,index) in btList"
                :key="index"
                :size="item.size"
                type="text"
                :icon="item.icon"
                @click="clickFun(item,scope.row)"
            >{{ item.label }}
            </el-button>
          </div>

        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="title" :visible.sync="open" :width="dialogWidth" append-to-body>
      <div class="dia-body">
        <el-scrollbar>
          <el-form :label-position="labelPosition" ref="valueForm" :model="form" :rules="rules" :label-width="dialogFormLabelWidth">
            <el-form-item v-for="(item,index) in valueConfig" :label="item.label" :prop="item.value">
              <el-input
                  v-if="item.type=='input'"
                  v-model="form[item.value]"
                  :placeholder="`请输入${item.label}`"
                  clearable
              >
              </el-input>
              <el-input
                  v-if="item.type=='txtArea'"
                  type="textarea"
                  v-model="form[item.value]"
                  :placeholder="`请输入${item.label}`"
                  clearable
              >
              </el-input>
              <el-input
                  v-if="item.type=='number'"
                  type="number"
                  v-model="form[item.value]"
                  :placeholder="`请输入${item.label}`"
                  clearable
              >
              </el-input>
              <choose-question
                  v-if="item.type=='choose-question' && open"
                  v-model="form[item.value]"></choose-question>


              <template v-if="item.type=='file'" slot="label">
                文件列表
              </template>
              <show-file-list :uid="form.rowId" v-if="item.type=='file'"
                              :file-list="allFileList.find(fileItem => fileItem.uid == `${form.rowId}-${item.value}`) == null ? [] : allFileList.find(fileItem => fileItem.uid == `${form.rowId}-${item.value}`).fileList"
                              @delFile="delFile"></show-file-list>
              <el-button v-if="item.type=='file'" class="file-upload-bt" icon="el-icon-refresh" size="mini"
                         @click="upload((`${form.rowId}-${item.value}`))">上传文件
              </el-button>


              <el-date-picker
                  value-format="yyyy-MM-dd"
                  type="date"
                  placeholder="选择日期"
                  v-if="item.type=='time'"
                  v-model="form[item.value]"
                  clearable
                  style="width: 100%; ">
              </el-date-picker>
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addRow">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {isArr} from "@/utils/arrayUtil";
import guid from "@/utils/guid";
import {isArray} from "lodash";
import ChooseQuestion from "@/views/components/ChooseQuestion/index.vue";
import ShowFileList from "@/components/ShowFileList/index.vue";
import {UploadFileObj} from "@/utils/uploadFile";
import {getQuestionLabelById} from "@/views/components/ChooseQuestion/chooseQuestionUtil";

export default {
  components: {
    ChooseQuestion,
    ShowFileList,
  },
  props: {
    btList: {
      type: Array
    },
    value: {
      type: Array,
      default: () => []
    },
    valueConfig: {
      type: Array
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    dialogWidth: {
      type: String,
      default: '530px'
    },
    dialogFormLabelWidth: {
      type: String,
      default: '100px'
    },
    addTitle: {
      type: String,
      default: '添加日志'
    },
    updateTitle: {
      type: String,
      default: '添加日志'
    },
    handWidth:{
      type:String,
      default:'100px'
    },
    labelPosition:{
      type:String,
      default:'left'
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    const CON_TYPE = {
      SHOW: 'SHOW',
      OPERATE: 'OPERATE'
    }
    return {
      valueList: [],
      showList: [],
      CON_TYPE,
      open: false,
      form: {},
      title: ''
    }
  },
  computed: {
    allFileList() {
      let res = this.$store.state.temporaryFile.temporaryFileList
      return isArr(res) ? res : []
    },
    rules() {
      let {valueConfig} = this
      let res = {}
      valueConfig.forEach(item =>{
        let {required,value,label} = item
        if (required){
          res[value] =  [
            {required: true, message: `${label}不能为空`, trigger: "change"}
          ]
        }
      })
      return res;
    }
  },
  watch: {
    value: {
      handler(val) {
        if (!isArr(this.showList) && isArr(val)) {
          this.showList = val
        }
      },
      deep: true,
    },
    showList: {
      handler(val) {
        let res = isArr(val) ? _.cloneDeep(val).map(item => {
          delete item.conType
          delete item.rowId
          return item
        }) : []
        this.$emit('change', res)
      },
      deep: true,
    }
  },
  methods: {
    getQuestionLabelById,
    //删除附件列表中附件回调函数
    delFile(item, uid) {
      let owner = this
      this.$modal.confirm('是否确认删除该数据项？').then(function () {
        let {fileId, fileName,} = item
        owner.$store.dispatch("temporaryFile/removeProjectDoc", {uid, fileId, fileName,},).then(() => {
          owner.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      })
    },
    upload(uid) {
      let uploadObj = UploadFileObj.getInstance();
      uploadObj.uploadFile('temporaryFile/addDoc', {uid})
    },
    clickFun(item, data) {
      this.$emit('clickFun', item, data)
    },
    isArr,
    cancel() {
      this.open = false
    },
    reset() {
      let rowItem = {};
      let {valueConfig, CON_TYPE} = this;
      valueConfig.forEach(rowConfig => {
        let {value} = rowConfig;
        rowItem[value] = null;
        rowItem.rowId = `row${guid()}`
      })
      this.form = rowItem;
    },
    handleAdd() {
      this.open = true;
      this.title = this.addTitle;
      this.reset();
    },
    arraySpanMethod({row, column, rowIndex, columnIndex}) {
      return [1, row?.mergeRow ? this.valueConfig.length + 1 : 1]
    },
    addRow() {
      let owner = this
      this.$refs["valueForm"].validate(valid =>{
        if (valid){
          let {form, CON_TYPE, valueConfig} = owner;
          if (owner.showList.length > 0) {
            owner.showList[owner.showList.length - 1].conType = CON_TYPE.SHOW
          }
          if (valueConfig.some(item => item.type == 'file')) {
            let {allFileList} = owner
            valueConfig.forEach(config => {
              let {type, value} = config
              if (type == 'file') {
                form[value] = allFileList.find(fileItem => fileItem.uid == `${form.rowId}-${value}`) == null ? [] : allFileList.find(fileItem => fileItem.uid == `${form.rowId}-${value}`).fileList.map(file => {
                  return file.fileId
                })
              }
            })
          }
          owner.cancel()
          if (owner.showList.some(item => item.rowId == form.rowId)) {
            owner.showList = _.cloneDeep(owner.showList).map(item => {
              item = item.rowId == form.rowId ? _.cloneDeep(form) : item
              return item
            });
          } else {
            owner.showList.push(form)
          }
        }
      })
    },
    updateRow(row) {
      let {CON_TYPE} = this;
      row.conType = CON_TYPE.OPERATE
      this.form = _.cloneDeep(row);
      this.open = true
      this.title = this.updateTitle;
    },
    removeRow(row) {
      let {rowId} = row
      this.showList = _.cloneDeep(this.showList).filter(item => item.rowId !== rowId)
    },
  },
  created() {
    this.valueList = this.value;
    if (!isArr(this.showList)) {
      let {CON_TYPE} = this
      this.showList = (isArr(this.value) ? this.value : []).map(item => {
        item.rowId = `row${guid()}`
        item.conType = CON_TYPE.SHOW;
        return item
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/style/businessTheme.scss";

.value-table-root {
  .handel-row {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }


  ::v-deep .el-button {
    height: 32px;

    &.el-button--primary {
      background: $bt-color;
      border: none;
    }
  }
}
</style>
